<template>
	<view class="main">
		  <u-navbar
		            title="搜索"
		            :autoBack="true"
		        >
		        </u-navbar>
		<view class="search_box">
			<u-search placeholder="搜索医院、科室、医生、疾病" :clearabled="true" :animation="false" :showAction="true"
				actionText="搜索" :focus="true" v-model="PopUpSarCh" @custom="inputGoHosp" @search="inputGoHosp"
				@change="btnBClick"></u-search>
		</view>
		<view v-if="active == true">
			<view class="tips" v-if="historyList.length > 0">
				<view class="tips_content">
					<view class="tips_title_box">
						<view class="tips_title">历史搜索</view>
						<view class="trash" @click="hisDel"><u-icon name="trash" size="20"></u-icon></view>
					</view>
					<view class="tips_brand">
						<view class="tips_brand_item" v-for="v in historyList" :key="v.id" @click="goDetails(v,'word')">
							{{myText(v.word)}}
						</view>
					</view>
				</view>
			</view>
			<view class="tips hot">
				<view class="tips_content">
					<view class="tips_title bold">热门搜索</view>
					<view class="tips_brand">
						<view class="tips_brand_item" v-for="v in hotList" :key="v.sort" @click="goDetails(v,'name')">
							{{myText(v.name)}}
						</view>
					</view>
				</view>
			</view>
		</view>
		<view v-if="active == false">
			<view class="box">
				<view class="SearchResults">
					<view class="SearchContent" v-for="(item, index) in records">
						<view class="rich_text" @click="goHosp(item)">
							<rich-text :nodes="item.ceshi"></rich-text>
						</view>

					<!-- 	<view class="sear_result">
							共有<span class="sear_num">{{item.count}}</span>个结果
						</view> -->
					</view>
				</view>
			</view>
		</view>
		<view v-if="list.length < 1 && active == false">
			<view class="tips" v-if="historyList.length > 0">
				<view class="tips_content">
					<view class="tips_title_box">
						<view class="tips_title">历史搜索</view>
						<view class="trash" @click="hisDel"><u-icon name="trash" size="20"></u-icon></view>
					</view>
					<view class="tips_brand">
						<view class="tips_brand_item" v-for="v in historyList" :key="v.id" @click="goDetails(v,'word')">
							{{myText(v.word)}}
						</view>
					</view>
				</view>
			</view>
			<view class="tips hot">
				<view class="tips_content">
					<view class="tips_title bold">热门搜索</view>
					<view class="tips_brand">
						<view class="tips_brand_item" v-for="v in hotList" :key="v.sort" @click="goDetails(v,'name')">
							{{myText(v.name)}}
						</view>
					</view>
				</view>
			</view>
		</view>
		<u-modal :show="showDel" @confirm="confirm" ref="uModal" :async-close="true" content="是否要删除历史记录"
			:showCancelButton="true" @cancel="cancel"></u-modal>
	</view>
</template>

<script>
	import parse from 'mini-html-parser2'
	import homeApi from '@/api/home'
	import {
		searchThink,
		getHistoryList,
		getHotRecommend,
		postKeyWord,
		delHistory
	} from '@/api/home/search.js'
	import {
		mapMutations
	} from 'vuex'
	export default {
		data() {
			return {
				hotList: [],
				historyList: [],
				active: true,
				list: [],
				PopUpSarCh: "",
				show: false,
				records: [],
				content: "",
				showDel: false,
				searchTopData: [],
			};
		},
		methods: {
			...mapMutations(['GETTOKEN','NAVGETDATA']),
			goSearch(value) {
				this.active = false
			},
			async addHis() { //添加搜索记录
				let params = {
					keyWord: this.$store.state.doc.keyWord.value,
					type: this.$store.state.doc.keyWord.type,
					precise: this.$store.state.doc.keyWord.precise,
				}
				// if(this.$store.state.doc.navCity.id){
				// 	params.city = this.$store.state.doc.navCity.id
				// }
				// if(this.$store.state.doc.zone.id){
				// 	params.countyId = this.$store.state.doc.zone.id
				// }
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				//console.log(params,123333777);
				let res = await postKeyWord(params)
				this.searchTopData = res.data
				this.$store.state.doc.searchTopData = res.data
				uni.hideLoading()
			},
			btnBClick() {
				// 此处用法为在js中调用，需要写uni.$u.throttle()
				//节流调用之前，情况数据
				this.list = [];
				this.records = []
				uni.$u.throttle(this.onSearch, 300) //节流
			},
			async onSearch() {
				//每次搜索前清空
				this.$store.state.doc.PopUpSarCh = this.PopUpSarCh //存入vuex中，供其他页面调用
				//console.log(this.$store.state.doc.PopUpSarCh);
				this.list = [];
				this.records = []
				if (this.PopUpSarCh) {
					let res = await searchThink(this.PopUpSarCh)
					//console.log(res);
					// if (res.code !== 4000) {
					// 	this.$u.toast('搜索结果异常', 2000)
					// 	return
					// }
					this.list.push(...res.data.hos, ...res.data.dept, ...res.data.doctor, ...res.data.disease);
					this.changeColor(this.list); //调用搜索词方法
				}
			},
			changeColor(result) {
				let searchWordList = this.PopUpSarCh.split('')
				//console.log(searchWordList)
				//result为接口返回的数据
				result.map((item, index) => {
					if (this.PopUpSarCh) {
						searchWordList.map((v, k) => {
							//	let replaceReg = new RegExp(this.PopUpSarCh, "ig");
							let replaceReg = new RegExp(v, "ig");
							//let replaceString = `<span style="color: #ed4014">${this.PopUpSarCh}</span>`;
							let replaceString = `<span style="color: #1677FF ">${v}</span>`;
							result[index].count = item.count;
							result[index].id = item.id;
							if (k == 0) { //第一次进入获得返回的关键词，第二次遍历就不去赋值，避免添加span标签
								result[index].source = item.name
							}
							result[index].name = item.name.replace(replaceReg, replaceString);
							//console.log(v,item);
						})

					} else {
						this.$nextTick(() => {
							this.records = [] //用户清除搜索结果，列表清空
						})
					}
				});
				this.records = result;
				//console.log(this.records, "123")
				let htmlNodes = []; //声明（防报错，不报错也可以不声明）
				this.records.forEach(el => {
					parse(el.name, (err, htmlNode) => {
						if (!err) {
							//console.log(htmlNode);
							el.ceshi = htmlNode
						}
					})
				})
			},

			open() {
				// console.log('open');
			},
			close() {
				this.show = false
				// console.log('close');
			},
			async topBtn(){
				await this.addHis() //添加搜索记录
				//console.log(this.searchTopData,'ooooo');
				this.NAVGETDATA()
			},
			async goDetails(keyWord, type) {  //历史搜索和热门搜索
				// console.log(keyWord,type);
				// return
				if (type == 'word') {
					this.$store.state.doc.keyWord.value = keyWord.word
					this.$store.state.doc.keyWord.type = keyWord.type
				}
				if (type == 'name') {
					this.$store.state.doc.keyWord.value = keyWord.name
					this.$store.state.doc.keyWord.type = keyWord.type
					this.$store.state.doc.keyWord.precise = false //全部设为false，因为结果的不确定性
				}
				if ([1, 2, 3].includes(keyWord.type)) {
					//console.log(type,'sfsdfsdf');
					this.$store.state.doc.topSearchButton = keyWord.type //0：未知 1:医院 2:科室 3:专家 4:疾病
				}
				this.topBtn()
			},
			async inputGoHosp() {  //强行搜索
				// 	console.log(this.list.length,111);
				// return
				if (!this.PopUpSarCh) {
					//	console.log(uni.$u.);
					uni.$u.toast('请输入搜索内容!')
					return
					//this.$u.toast('请输入搜索内容',2000)
				} else {
					this.$store.state.doc.keyWord.value = this.PopUpSarCh
					this.$store.state.doc.keyWord.type = 0
					this.$store.state.doc.keyWord.precise = false
					this.topBtn()
				}
			},
			async goHosp(params) {  //点击搜索提示，因为肯定能返回type类型，所以跟历史，强行搜索做区别
				if(params.type == 4){
					this.$store.state.doc.keyWord.value = params.diseaseName
				}else{
					this.$store.state.doc.keyWord.value = params.source
				}
				// console.log(params,'aaaaaa');
				// return
				this.$store.state.doc.keyWord.type = params.type
				this.$store.state.doc.keyWord.precise = false //这里暂时把精准去掉，不然有时候搜着搜着结果不一样
				//跳转逻辑
				if(params.type == 1){  //跳转医院
					await this.addHis() //添加搜索记录
					this.$store.state.doc.currentHosp.hospitalId = params.id
					uni.navigateTo({
						url: '/pages/sousuo/search_hosp_details/index'
					});
					return
				}
				// if(params.type == 3){  //跳转医院
				// 	await this.addHis() //添加搜索记录
				// 	this.$store.state.doc.currentHosp.hospitalId = params.id
				// 	uni.navigateTo({
				// 		url:`/pages/sousuo/search_dep_details/index?departmentId=${params.childdeptId}`
				// 	})
				// }
				//跳转逻辑结束
				//下面是走搜索结果页面
				this.topBtn()
			},
			async confirm() {
				let res = await delHistory()
				this.showDel = false
				this.hisList()
			},
			cancel() {
				this.showDel = false
			},
			hisDel() { //删除搜索历史
				this.showDel = true
			},
			async reconList() { //热门推荐列表
				let res = await getHotRecommend()
				//console.log(res);
				this.hotList = res.data
				//console.log(this.hotList)
			},
			async hisList() { //搜索历史列表
				let res = await getHistoryList()
				this.historyList = res.data.list
				//console.log(this.historyList.length)
			}

		},
		async onLoad() {
			let token = uni.getStorageSync("token")
			if (!token) {
			 await this.GETTOKEN()
			}else{
				
			}
			this.reconList()
			this.hisList()
		},
		onShow() {
			// my.setNavigationBar({
			// 	title: '搜索',
			// })
		},
		computed: {
			myText(value) {
				return (value) => {
					if (value.length > 20) {
						//console.log(value.length);
						return value.slice(0, 19) + '...'
					}
					return value
				}
			},
		},
		watch: {
			'$store.state.doc.PopUpSarCh'(ne, old) {
				//console.log(ne);
				if (ne.length == 0) {
					this.active = true
				} else {
					this.active = false
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.main {
		background-color: #fff;
		//height: 100vh;

		.search_box {
			margin: 0 30rpx;
			margin-top: 200rpx;
		}

		.tips {
			margin-top: 16rpx;

			.tips_content {
				padding-left: 20rpx;

				.tips_title_box {
					display: flex;
					justify-content: space-between;
					align-items: center;
					text-align: center;
					padding-top: 20rpx;

					.tips_title {
						font-weight: 600;
					}

					.trash {
						padding-right: 20rpx;
					}
				}

				.tips_brand {
					display: flex;
					flex-direction: row;
					//justify-content: space-between;

					flex-wrap: wrap;
					align-items: center;

					.tips_brand_item {
						//flex: 0 0 23%;
						text-align: center;
						border-radius: 30rpx;
						border: 1px solid #eee;
						background-color: #eee;
						margin-top: 30rpx;
						margin-right: 40rpx;
						padding: 10rpx 16rpx;
					}

					// .tips_brand_item:nth-child(3n+3) {
					// 	margin-right: 100rpx;
					// }

					// .tips_brand_item:nth-child(3n+1) {
					// 	margin-left: 20rpx;
					// }
				}
			}

		}

		.hot {
			padding-top: 20rpx;
		}

		.bold {
			font-weight: 600;
		}

		//height: 100vh;

		.box {
			padding-bottom: 50rpx;

			.SearchResults {
				margin-top: 10rpx;

				.SearchContent {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 10rpx 30rpx;
					font-size: 28rpx;
					font-weight: 400;
					color: #3D3D3D;
					line-height: 34rpx;

					.rich_text {
						flex:1;
						background: #F5F6F8;
						border-radius: 26rpx;
						margin-right: 10rpx;
					}

					.sear_result {
						flex-shrink: 0;
						font-size: 24rpx;
						font-weight: 400;
						color: #999999;
						line-height: 34rpx;
						padding-bottom: 6rpx;
						.sear_num {
							//font-size: 22rpx;
							color: #3D3D3D;
						}
					}
				}
			}
		}

	}
</style>